package com.huanying.goodjob.store;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.huanying.framework.BaseController;
import com.huanying.framework.PageBean;
import com.huanying.framework.adminuser.Adminuser;
import com.huanying.goodjob.business.BusinessList;
import com.huanying.goodjob.business.BusinessListService;
import com.huanying.goodjob.community.Area;
import com.huanying.goodjob.community.CommunityService;

@Controller
public class StoreController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private BusinessListService businessListService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private CommunityService communityService;
	private static Logger logger = Logger.getLogger(StoreController.class);
	// 查询店铺
	@RequestMapping("/show_add_store.do")
	public String show_add_store(String shopname, String type, String shopmanagename,String phone, String page_num, String introduce,
			 Model model) {
		Adminuser user=(Adminuser) this.getSession().getAttribute("user");
		PageBean pageBean = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shopname", shopname);
		map.put("type", type);
		map.put("name", shopmanagename);
		map.put("introduce", introduce);
		map.put("phone", phone);
		if(user.getRole()!=1)
		{
			map.put("user",user);
		}
		if (page_num == null) {
			page_num = "1";
		}
		try {
			pageBean = storeService.search_store(map, super.getPageSize(), Integer.parseInt(page_num));
			logger.info("查询展示工单信息成功");
		} catch (NumberFormatException e) {
			logger.error("查询展示工单信息失败", e);
			// e.getMessage();
		} catch (Exception e) {
			logger.error("查询展示工单信息失败", e);
			// e.getMessage();
		}
		model.addAttribute("user", user);
		model.addAttribute("shopname", shopname);
		model.addAttribute("shopmanagename", shopmanagename);
		model.addAttribute("type", type);
		model.addAttribute("introduce", introduce);
		model.addAttribute("storelist", pageBean.getList());
		model.addAttribute("page", pageBean);
		return "/store/add_store";
	}

	// 添加和修改店铺
	@RequestMapping("/add_store.do")
	@ResponseBody
	public Map<String, Object> add_store(String shopname, String shopmanagename, String phone, String type,
			@RequestParam("file") MultipartFile image_01, String introduce, String id, String status,String province_code, String city_code, String county_code) {
		Map<String, Object> map = new HashMap<String, Object>();
		Adminuser user=(Adminuser) this.getSession().getAttribute("user");
		Store store = new Store();
		String file_name = "";
		String filePath = null;
		store.setShopname(shopname);
		store.setShopmanagename(shopmanagename);
		store.setPhone(phone);
		store.setIntroduce(introduce);
		store.setType(Integer.parseInt(type));
		store.setUser(user);
		Area province;
		try {
			System.out.println(province_code);
			province = communityService.getbyCode(province_code);
			store.setProvince(province);
			Area city = communityService.getbyCode(city_code);
			store.setCity(city);
			Area county = communityService.getbyCode(county_code);
			store.setCounty(county);
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			logger.error("获取区域失败", e2);
		}	
		if (!image_01.isEmpty()) {
			String temp_name = image_01.getOriginalFilename();
			String postfix = temp_name.substring(temp_name.lastIndexOf("."), temp_name.length());
			/**
			 * javaJDK提供的一个自动生成主键的方法 生成唯一的文件名
			 */
			file_name = UUID.randomUUID().toString() + postfix;
		//	filePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload" + File.separator
		//			+ "store" + File.separator + file_name;
			filePath ="/opt/fileUpload" + File.separator
							+ "store" + File.separator + file_name;
			logger.info(filePath);
			try {
				// 获得上传时的文件名		
				image_01.transferTo(new File(filePath));	
				logger.info("You successfully uploaded");
			} catch (Exception e) {
				logger.error("You failed to upload", e);
				map.put("flag","3");
				return map;
			}
			String realfliePath = "fileUpload" + File.separator + "store" + File.separator + file_name;
			store.setTradeimg_url(realfliePath);
		} else {
			logger.info("You failed to upload because the file was empty.");
		}
		if (Integer.parseInt(id) == 0) {
			store.setStatus(1);
			try {
				storeService.add_store(store);
				map.put("flag", "1");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if(filePath!=null)
				{
					new File(filePath).delete();
				}
				map.put("flag", "0");
				logger.error("添加店铺失败", e);
			}
		} else {
			store.setId(Integer.parseInt(id));
			store.setStatus(Integer.parseInt(status));
			try {
				if ((storeService.get_store(store.getId())).getTradeimg_url() != null
						&& store.getTradeimg_url() == null) {
					store.setTradeimg_url(storeService.get_store(store.getId()).getTradeimg_url());
				}
				if ((storeService.get_store(store.getId())).getBusinesslist() != null) {
					store.setBusinesslist(storeService.get_store(store.getId()).getBusinesslist());
					store.getBusinesslist().setStatus(Integer.parseInt(status));
				}
				if ((storeService.get_store(store.getId())).getLatitude() != null
						&& (storeService.get_store(store.getId())).getLongitude() != null) {
					store.setLatitude(storeService.get_store(store.getId()).getLatitude());
					store.setLongitude(storeService.get_store(store.getId()).getLongitude());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("获取单个店铺失败", e);
			}
			try {
				storeService.update_store(store);
				map.put("flag", "1");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if(filePath!=null)
				{
					new File(filePath).delete();
				}
				map.put("flag", "0");
				logger.error("修改店铺失败", e);
			}
		}
		map.put("id", Integer.parseInt(id));
		map.put("shopname", shopname);
		return map;
	}

	// 获取单个店铺
	@RequestMapping("/get_store.do")
	@ResponseBody
	public Map<String, Object> get_store(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Store store;
		try {
			store = storeService.get_store(Integer.parseInt(id));
			map.put("store", store);
			map.put("flag", "1");
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		}
		return map;
	}

	// 删除店铺
	@RequestMapping("/delete_store.do")
	@ResponseBody
	public Map<String, String> delete_store(String id) {
		Map<String, String> map = new HashMap<String, String>();
		Store store;
		try {
			store = storeService.get_store(Integer.parseInt(id));
			if (store.getBusinesslist() != null) {
				store.getBusinesslist().setStatus(0);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		}
		try {
			storeService.delete_store(Integer.parseInt(id));
			map.put("flag", "1");

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("删除店铺失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("删除店铺失败", e);
		}
		return map;
	}

	// 显示与添加店铺名称相同的工单
	@RequestMapping("/show_businessbyname.do")
	public String serarch_storebusuness(String store_id, Model model) {

		PageBean pageBean = null;
		Map<String, String> map = new HashMap<String, String>();
		Store store;
		try {
			store = storeService.get_store(Integer.parseInt(store_id));
			map.put("shopname", store.getShopname());
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		}

		try {
			pageBean = businessListService.searchBusiness(map, 3, 1);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("查询工单失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("查询工单失败", e);
		}
		model.addAttribute("store_id", store_id);
		model.addAttribute("businesslists", pageBean.getList());
		model.addAttribute("size",pageBean.getList().size() );
		model.addAttribute("page", pageBean);
		return "/store/store_relation";
	}

	// 店铺与工单关联
	@RequestMapping("/add_businessbyname.do")
	public String add_businessbyname(HttpServletRequest request, Model model) {
		BusinessList business = null;
		Store store = null;
		String[] checks = request.getParameterValues("checktd");
		String storeid = request.getParameter("storeid");
		try {
			store = storeService.get_store(Integer.parseInt(storeid));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个店铺失败", e);
		}
		if (checks != null) {
			for (int i = 0; i < checks.length; i++) {
				try {
					business = businessListService.get_byid(Integer.parseInt(checks[i]));
					store.setBusinesslist(business);
					store.setLatitude(business.getAddress_y());
					store.setLongitude(business.getAddress_x());
					business.setIs_relation(1);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					logger.error("获取单个工单失败", e);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("获取单个工单失败", e);
				}

				try {
					businessListService.update_business(business);
					model.addAttribute("flog", 1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					model.addAttribute("flog", 0);
					logger.error("更新工单失败", e);
				}
				try {
					storeService.update_store(store);
					model.addAttribute("flag", 1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					model.addAttribute("flag", 0);
					logger.error("更新店铺失败", e);
				}
			}
		} else {
			if (store.getBusinesslist() != null) {
				store.getBusinesslist().setIs_relation(0);

				store.setBusinesslist(null);
				store.setLatitude(null);
				store.setLongitude(null);

				try {
					storeService.update_store(store);
					model.addAttribute("flag", 3);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("更新店铺失败", e);
				}
			} else {
				model.addAttribute("store_id", storeid);
				model.addAttribute("flag", 4);
			}
		}
		return "/store/store_relation";
	}
	//前台获取店铺
	@RequestMapping("/front_get_store.do")
	@ResponseBody
	public String frontget_store(String jsoncallback,String province_code,String city_code,String county_code)
	{
		Map<String,Object> map=new HashMap<String,Object>();
		List<Store> stores=new ArrayList<Store>();
		Map<String,Object> map1=new HashMap<String,Object>();
		map1.put("province_code",province_code);
		map1.put("city_code",city_code);
		map1.put("county_code",county_code);
		try {
			stores=storeService.front_get_store(map1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("前台获取店铺失败", e);
		}
		map.put("list",stores);
		Gson gson=new Gson();
		String json="";
		json=gson.toJson(map);
		return jsoncallback+"("+json+")";
		}
}
